import React, { useEffect, useState } from "react";
import { getCityApi } from "../../api";
import { IndexBar, Space, Tag } from "antd-mobile";
import { useNavigate, useSearchParams } from "react-router-dom";
import { useDispatch } from "react-redux";
import { setEnd, setStart } from "../../store/home/homeSlice";

const City = () => {
  const [data, setData] = useState({});
  const [searchParams] = useSearchParams();
  const navigate = useNavigate()
  const type = searchParams.get('type')
  const dispatch = useDispatch()
  const handleClick = (city) => {
    if(type === 'start') {
      dispatch(setStart(city))
    } else {
      dispatch(setEnd(city))
    }
    navigate(-1)
  }
  const getData = async () => {
    const resp = await getCityApi();
    console.log(resp.data.data);
    setData(resp.data.data);
  };

  useEffect(() => {
    getData();
  }, []);
  return (
    <div style={{ height: '100vh' }}>
      <h2>热门城市</h2>
      <Space style={{ flexWrap: "wrap" }}>
        {data.hotCities &&
          data.hotCities.map((v, i) => {
            return (
              <Tag key={i} style={{ margin: 10 }}>
                {v.name}
              </Tag>
            );
          })}
      </Space>
      <IndexBar>
        {data.cityList &&
          data.cityList.map((v, i) => {
            return (
              <IndexBar.Panel key={i} index={v.title}>
                {v.citys.map((v, i) => {
                  return (
                    <h3
                      style={{
                        borderBottom: "1px solid #ccc",
                        lineHeight: "40px",
                      }}
                      key={i}
                      onClick={() => handleClick(v.name)}
                    >
                      {v.name}
                    </h3>
                  );
                })}
              </IndexBar.Panel>
            );
          })}
      </IndexBar>
      {/* hook.js:608 Error handled by React Router default ErrorBoundary: TypeError: Cannot read properties of undefined (reading 'map')
    at City (index.jsx:19:24)
 Error Component Stack
    at RouterProvider2 (<anonymous>)
    at div (<anonymous>)
    at App (<anonymous>) */}
    </div>
  );
};

export default City;
